package org.jeecg.modules.kuybFeilb.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.chexk.service.IKuybChexkService;
import org.jeecg.modules.chexk.vo.Data;
import org.jeecg.modules.chexkChex.entity.KuybChexkChex;
import org.jeecg.modules.chexkChex.service.IKuybChexkChexService;
import org.jeecg.modules.chexkModel.entity.KuybChexkModel;
import org.jeecg.modules.chexkModel.service.IKuybChexkModelService;
import org.jeecg.modules.kuybCarTrain.entity.KuybCarTrain;
import org.jeecg.modules.kuybCarTrain.service.IKuybCarTrainService;
import org.jeecg.modules.kuybFeilb.entity.KuybFeilb;
import org.jeecg.modules.kuybFeilb.service.IKuybFeilbService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.suanfrz.entity.KuybSuanfrz;
import org.jeecg.modules.suanfrz.service.IKuybSuanfrzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: kuyb_feilb
 * @Author: jeecg-boot
 * @Date: 2021-09-13
 * @Version: V1.0
 */
@Api(tags = "费率管理")
@RestController
@RequestMapping("feilb/kuybFeilb")
@Slf4j
public class KuybFeilbController extends JeecgController<KuybFeilb, IKuybFeilbService> {
    @Autowired
    IKuybSuanfrzService kuybSuanfrzService;

    @Autowired
    private IKuybFeilbService kuybFeilbService;
    @Autowired
    private IKuybCarTrainService carTrainService;

    @Autowired
    private IKuybChexkModelService kuybChexkModelService;

    @Autowired
    private IKuybChexkChexService kuybChexkChexService;

    /**
     * 分页列表查询
     *
     * @param kuybFeilb
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "kuyb_feilb-分页列表查询")
    @ApiOperation(value = "kuyb_feilb-分页列表查询", notes = "kuyb_feilb-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(KuybFeilb kuybFeilb,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<KuybFeilb> queryWrapper = QueryGenerator.initQueryWrapper(kuybFeilb, req.getParameterMap());
        Page<KuybFeilb> page = new Page<KuybFeilb>(pageNo, pageSize);
        IPage<KuybFeilb> pageList = kuybFeilbService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param kuybFeilb
     * @return
     */
    @AutoLog(value = "kuyb_feilb-添加")
    @ApiOperation(value = "kuyb_feilb-添加", notes = "kuyb_feilb-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody KuybFeilb kuybFeilb) {
        kuybFeilbService.save(kuybFeilb);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param kuybFeilb
     * @return
     */
    @AutoLog(value = "kuyb_feilb-编辑")
    @ApiOperation(value = "kuyb_feilb-编辑", notes = "kuyb_feilb-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody KuybFeilb kuybFeilb) {
        kuybFeilbService.updateById(kuybFeilb);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "kuyb_feilb-通过id删除")
    @ApiOperation(value = "kuyb_feilb-通过id删除", notes = "kuyb_feilb-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        kuybFeilbService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "kuyb_feilb-批量删除")
    @ApiOperation(value = "kuyb_feilb-批量删除", notes = "kuyb_feilb-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.kuybFeilbService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "kuyb_feilb-通过id查询")
    @ApiOperation(value = "kuyb_feilb-通过id查询", notes = "kuyb_feilb-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        KuybFeilb kuybFeilb = kuybFeilbService.getById(id);
        if (kuybFeilb == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(kuybFeilb);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param kuybFeilb
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, KuybFeilb kuybFeilb) {
        return super.exportXls(request, kuybFeilb, KuybFeilb.class, "kuyb_feilb");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, KuybFeilb.class);
    }

    /**
     * 前端获取保费
     *
     * @param kuybFeilb
     * @param request
     * @return
     */
    @AutoLog(value = "kuyb_feilb-根据车型名称，里程，初登日期，质保时长获取保费")
    @ApiOperation(value = "前端获取保费", notes = "前端获取保费")
    @GetMapping(value = "/getPremiumByParam")
    public Result<?> getPremiumByParam(KuybFeilb kuybFeilb, HttpServletRequest request) {
		KuybSuanfrz kuybSuanfrz = new KuybSuanfrz();
		kuybSuanfrz.setProductId(kuybFeilb.getProductId());
		kuybSuanfrz.setCarId(kuybFeilb.getCarId());
		kuybSuanfrz.setChudrq(DateUtil.format(kuybFeilb.getChudrq(), "yyyy-MM-dd"));
		kuybSuanfrz.setXingslc(kuybFeilb.getXingslc());
		kuybSuanfrz.setGoumnx(kuybFeilb.getGoumnx());

		kuybSuanfrzService.save(kuybSuanfrz);
		log.info("记录算费日志成功");
        //行驶里程超过原厂保障里程+购买里程不予承保
        if(150000<Integer.parseInt(kuybFeilb.getXingslc())){
            return Result.error(201, "行驶里程超过15万！");
        }

//         Data d=kuybChexkService.queryCarBasicByCarId(kuybFeilb.getCarId()); //从阿里查询车型信息
        KuybChexkModel d = kuybChexkModelService.getById(kuybFeilb.getCarId());
        if (d == null) {
            return Result.error(201, "请选择车型");
        }


//         String warrantypolicy=d.getBasic().getWarrantypolicy();
       /*  String nian="";
         String gongli="";

         if(warrantypolicy.contains("或")){
             String[] st=warrantypolicy.split("或");
             if(st[0].contains("年")){
                 nian=st[0].replace("年","");
                 gongli=st[1].replace("万公里","");
             }else {
                 nian=st[1].replace("年","");
                 gongli=st[0].replace("万公里","");
             }
         }else{
             nian=warrantypolicy.replace("年","");
             gongli="10";
         }

         try{
             kuybFeilb.setWarrantyPolicyMileage(Integer.parseInt(gongli)*10000);//原厂保修里程
             kuybFeilb.setWarrantyPolicyTime(Integer.parseInt(nian)<3 ? 3:Integer.parseInt(nian));//原厂保修年
         }catch (Exception e){
             kuybFeilb.setWarrantyPolicyMileage(100000);//原厂保修里程
             kuybFeilb.setWarrantyPolicyTime(3);//原厂保修年
         }*/

        kuybFeilb.setPolicyTimeMileage(kuybFeilb.getGoumnx());
        if (kuybFeilb.getGoumnx().contains("$")) {
            kuybFeilb.setGoumlc(kuybFeilb.getGoumnx().split("\\$")[1]);
            kuybFeilb.setGoumnx(kuybFeilb.getGoumnx().split("\\$")[0]);
        }
        int yue = 0;
        try {
            yue = getMonthSpace(kuybFeilb.getChudrq(), new Date());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(60<yue){
            return Result.error(201, "购买时长超过60个月！");
        }
        String priceStr = d.getJiag() + "";
        if (priceStr.contains("万")) {
            kuybFeilb.setPriceStart(new BigDecimal(priceStr.replace("万", "")).multiply(new BigDecimal(10000)));
        } else {
            kuybFeilb.setPriceStart(new BigDecimal(priceStr).multiply(new BigDecimal(10000)));
        }
        kuybFeilb.setNengylx(d.getNengylx());//能源类型 1 油，2 混动 3，纯电
        KuybChexkChex chexkChex = kuybChexkChexService.getById(d.getChex());
//        KuybCarTrain carTrain = carTrainService.getCarTrainByCarName(chexkChex.getFenl());//获取车系
//        if(carTrain == null)
//            return Result.error("获取车系失败: " + chexkChex.getFenl());

//        kuybFeilb.setCarTrain(carTrain.getCarcode());
        kuybFeilb.setCarTrain("1");
        kuybFeilb.setIsImport(d.getShifjk() + "");

        //日产车 特殊处理 如果原厂质保是5年，那默认原厂里程是15万
      /*  if(kuybFeilb.getWarrantyPolicyTime()==5 && kuybFeilb.getCarTrain().equals("5")&& kuybFeilb.getNengylx().equals("1")){
            kuybFeilb.setWarrantyPolicyMileage(100000);//原厂保修里程
            kuybFeilb.setWarrantyPolicyTime(3);//原厂保修年
        }else {*/
            try {
                kuybFeilb.setWarrantyPolicyMileage(d.getYuancbxgls());//原厂保修里程
                if (d.getYuancbxgls() == 0)
                    kuybFeilb.setWarrantyPolicyMileage(100000);//原厂保修里程

                kuybFeilb.setWarrantyPolicyTime(d.getYuancbxnx());//原厂保修年
                if (d.getYuancbxnx() == 0)
                    kuybFeilb.setWarrantyPolicyTime(3);//原厂保修年
            } catch (Exception e) {
                kuybFeilb.setWarrantyPolicyMileage(100000);//原厂保修里程
                kuybFeilb.setWarrantyPolicyTime(3);//原厂保修年
            }
//        }

        kuybFeilb.setServiceLifeStart(yue);
        if (d.getNengylx().equals("1")) {
//            if (carTrain == null) {
//                return Result.error(201, "暂时不承保该车型");
//            }
//            kuybFeilb.setCarTrain("");
            kuybFeilb.setIsImport(d.getShifjk() + "");
        } else {//如果是 新能源和混动 怎 不区分 车系和是否进口，这两项全部设置为0
            kuybFeilb.setIsImport("0");
            kuybFeilb.setCarTrain("0");
            kuybFeilb.setWarrantyPolicyTime(8);//原厂保修年
        }

        //如果车辆过原厂保修，且不超过5年则按照最近一档承保
        if(yue>60){
            return Result.error(201, "车辆登记日期超过5年，暂不承保");
        }
        if(yue>(kuybFeilb.getWarrantyPolicyTime()*12) && yue<=48){
            kuybFeilb.setWarrantyPolicyTime(4);
        }else if(yue>(kuybFeilb.getWarrantyPolicyTime()*12)){
            kuybFeilb.setWarrantyPolicyTime(5);
        }


        KuybFeilb feilb = kuybFeilbService.getPremiumByParam(kuybFeilb);
        if (feilb == null) {
            return Result.error(201, "暂时不承保该车型");
        }

        feilb.setWarrantyPolicyMileage(kuybFeilb.getWarrantyPolicyMileage());//原厂保修里程
        feilb.setWarrantyPolicyTime(kuybFeilb.getWarrantyPolicyTime());//原厂保修年
        feilb.setCarTrain(kuybFeilb.getCarTrain());
        feilb.setIsImport(kuybFeilb.getShifjk());

        kuybSuanfrz.setSuanfjg(JSON.toJSONString(feilb));
		kuybSuanfrzService.updateById(kuybSuanfrz);

        return Result.OK(feilb);
    }


    /**
     * 根据车型名称，产品ID获取承保规格
     *
     * @param kuybFeilb
     * @param request
     * @return
     */
    @AutoLog(value = "kuyb_feilb-根据车型名称，产品ID获取承保规格")
    @ApiOperation(value = "根据车型名称，产品ID获取承保规格", notes = "根据车型名称，产品ID获取承保规格")
    @GetMapping(value = "/getStandards")
    public Result<?> getStandards(KuybFeilb kuybFeilb, HttpServletRequest request) {

        KuybChexkModel d = kuybChexkModelService.getById(kuybFeilb.getCarId());
        if (d == null) {
            return Result.error(201, "请选择车型");
        }


        try {
            kuybFeilb.setWarrantyPolicyMileage(d.getYuancbxgls());//原厂保修里程
            if (d.getYuancbxgls() == 0)
                kuybFeilb.setWarrantyPolicyMileage(100000);//原厂保修里程

            kuybFeilb.setWarrantyPolicyTime(d.getYuancbxnx());//原厂保修年
            if (d.getYuancbxnx() == 0)
                kuybFeilb.setWarrantyPolicyTime(3);//原厂保修年
        } catch (Exception e) {
            kuybFeilb.setWarrantyPolicyMileage(100000);//原厂保修里程
            kuybFeilb.setWarrantyPolicyTime(3);//原厂保修年
        }
        int yue = 0;
        try {
            yue = getMonthSpace(kuybFeilb.getChudrq(), new Date());
        } catch (ParseException e) {
            return Result.OK(null);
        }

        //如果车辆过原厂保修，且不超过5年则按照最近一档承保
        if(yue>60){
            return Result.error(201, "车辆登记日期超过5年，暂不承保");
        }
        if(yue>(kuybFeilb.getWarrantyPolicyTime()*12) && yue<=48){
            kuybFeilb.setWarrantyPolicyTime(4);
        }else if(yue>(kuybFeilb.getWarrantyPolicyTime()*12)){
            kuybFeilb.setWarrantyPolicyTime(5);
        }


        String priceStr = d.getJiag() + "";
        if (priceStr.contains("万")) {
            kuybFeilb.setPriceStart(new BigDecimal(priceStr.replace("万", "")).multiply(new BigDecimal(10000)));
        } else {
            kuybFeilb.setPriceStart(new BigDecimal(priceStr).multiply(new BigDecimal(10000)));
        }
        kuybFeilb.setNengylx(d.getNengylx());//能源类型 1 油，2 混动 3，纯电

//        kuybFeilb.setServiceLifeStart(yue);
        if (d.getNengylx().equals("1")) {
            KuybChexkChex chexkChex = kuybChexkChexService.getById(d.getChex());
           /* KuybCarTrain carTrain = carTrainService.getCarTrainByCarName(chexkChex.getFenl());
            if (carTrain == null) {
                return Result.error(201, "暂时不承保该车型");
            }
            kuybFeilb.setCarTrain(carTrain.getCarcode());*/
            kuybFeilb.setIsImport(d.getShifjk() + "");
        } else {//如果是 新能源和混动 怎 不区分 车系和是否进口，这两项全部设置为0
            kuybFeilb.setIsImport("0");
            kuybFeilb.setCarTrain("0");
            kuybFeilb.setWarrantyPolicyTime(8);//原厂保修年
        }

        List<KuybFeilb> feilbs = kuybFeilbService.getStandards(kuybFeilb);
        if (feilbs == null) {
            return Result.error(201, "暂时不承保该车型");
        }
        return Result.OK(feilbs);
    }



    public static int getMonthSpace(Date date1, Date date2)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        int result = 0;
        Calendar cal1 = new GregorianCalendar();
        cal1.setTime((date1));
        Calendar cal2 = new GregorianCalendar();
        cal2.setTime((date2));
        result = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
        return result == 0 ? 1 : Math.abs(result);
    }

}
